package org.tinycloud.tinyjob.config.runner;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.tinycloud.tinyjob.utils.quartz.InternalMonitorJob;


/**
 * <p>
 * 内置主机服务状态监控-启动时执行类
 * </p>
 *
 * @author liuxingyu01
 * @since 2025/8/22 20:53
 */
@Component
@Order(98)
public class MonitorApplicationRunner implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(MonitorApplicationRunner.class);

    private static final String jobGroup = "INTERNAL";

    private static final String jobName = "Host_Monitor";

    // 60秒执行一次
    private static final int intervalInSeconds = 60;

    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("Initialization MonitorApplicationRunner start!");

        // 判断定时任务是否已存在，不存在的话就创建
        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);

        if (!scheduler.checkExists(jobKey)) {
            logger.info("InternalMonitorJob start init!");
            JobDetail jobDetail = JobBuilder.newJob(InternalMonitorJob.class)
                    .withIdentity(jobKey) // 任务标识
                    .storeDurably() // 即使没有触发器关联也持久化保存
                    .build();

            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(intervalInSeconds) // 间隔时间，单位：秒
                    .repeatForever(); // 不限执行次数，无限次数，一直重复执行

            Trigger trigger = TriggerBuilder.newTrigger()
                    .forJob(jobDetail) // 关联任务
                    .withIdentity(triggerKey) // 触发器标识
                    .withSchedule(scheduleBuilder) // 关联调度器
                    .build();

            // 构建并且运行任务
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            logger.info("InternalMonitorJob already exists!");
        }

        logger.info("Initialization MonitorApplicationRunner end!");
    }
}

